//
//  WBRefreshControl.swift
//  微博(swift)
//
//  Created by 汤米 on 16/4/23.
//  Copyright © 2016年 汤米. All rights reserved.
//

import UIKit

private let RefreshHeight: CGFloat = 50

enum WBRefreshControlType: Int {
    
    //正常状态
    case Normal = 0
    //释放更新
    case Pulling = 1
    //加载中
    case Refreshing = 2
    
}

class WBRefreshControl: UIControl {
    
    // MARK: -  关于刷新状态属性
    var WBState: WBRefreshControlType = .Normal {
        
        didSet {
            
            switch WBState {
            case.Normal:
                messageLabel.text = "正常状态"
                self.alpha = 0
                if oldValue == .Refreshing {
                    
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        
                        self.scrollView?.contentInset.top -= RefreshHeight
                    })
                }
                 break
            case.Pulling:
                self.alpha = 1
                messageLabel.text = "释放更新"
                break
            case.Refreshing:
                self.alpha = 1
                messageLabel.text = "加载中"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.scrollView?.contentInset.top += RefreshHeight
                    }, completion: { (_) -> Void in
                        
                        //告知外界刷新数据
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                })
                break
            }
        }
    }
    
    // MARK: -  将scrollView记录
    var scrollView: UIScrollView?
    
    
    // MARK: -  通过该方法监听label添加到谁身上了
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        if let scrollView = newSuperview as? UIScrollView {
            
            //通过kvo监听父控件属性的改变
            self.scrollView = scrollView
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        }
    }
    
    // MARK: -  监听对象的哪个属性的变化
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //获取临界值
        let criticalState = -(RefreshHeight + (scrollView?.contentInset.top)!)
        let scrollState =  scrollView?.contentOffset.y
        
        if scrollView!.dragging {
            
            if scrollState > criticalState && WBState == .Pulling {
                
                WBState = .Normal
                
            }else if scrollState <= criticalState && WBState == .Normal {
                
                WBState = .Pulling
            }
        }else {
            
            if WBState == .Pulling {
                WBState = .Refreshing
            }
        }

    }
    
    // MARK: -  KVO需要程序员自己移除
    deinit {
        
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    // MARK: -  重写init方法
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setUpUI()
    }
    
    // MARK: -  重写init方法时候必须要实现的方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: -  供外界调用的方法  停止刷新
    func endRefreshing() {
        
        WBState = .Normal
        
    }
    
    // MARK: -  设置控件布局
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        self.frame = CGRect(x: 0, y: -RefreshHeight, width: kScreenW, height: RefreshHeight)
        messageLabel.frame = CGRect(x: 0, y: 0, width: kScreenW, height: RefreshHeight)
    }
    
    // MARK: -  设置视图
    func setUpUI() {
        backgroundColor = randumColor()
        WBState = .Normal
        addSubview(messageLabel)
    }

    // MARK: -  懒加载label
    private lazy var messageLabel: UILabel = {
        
        let messageLabel = UILabel()
        messageLabel.font = UIFont.systemFontOfSize(14)
        messageLabel.text = "正常状态"
        messageLabel.textAlignment = .Center
        messageLabel.textColor = UIColor.whiteColor()
        return messageLabel
    }()
    

}
